package cn.kerui.gateways.filter;

import cn.kerui.gateways.constants.GatewayConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;
import java.util.UUID;

/**
 * @author yangkai
 * @version 1.0.0
 * @ClassName MyLogGatewayFilter.java
 * 
 * @createTime 2023年05月05日 09:25:00
 */
@Component
@Slf4j
public class MyLogGatewayFilter implements GlobalFilter, Ordered {

    /**
     * 具体的实现过滤代码的方法
     * @param exchange the current server exchange
     * @param chain provides a way to delegate to the next filter
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("******************come in MyLogGatewayFilter: " + new Date());
//                .header(GatewayConstants.SOURCE_IP, )
        String traceId = UUID.randomUUID().toString();
        ServerHttpRequest request = exchange.getRequest()
                .mutate()
                .header(GatewayConstants.TRACE_ID, traceId)
                .header(GatewayConstants.REQUEST_NO, traceId)
                .build();

        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add(GatewayConstants.TRACE_ID, traceId);
        log.info("请求已转发到指定服务requestNo={}, url={}", traceId, request.getURI());

        return chain.filter(exchange.mutate().request(request).build());
    }

    /**
     * 加载过滤器的顺序，数字越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
